package com.sx.gateway.controller;

import com.sx.code.CodeDubboService;
import com.sx.email.EmailService;
import com.sx.user.UserDubboService;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

/**
 * @author shengx
 * @date 2020/5/25 13:24
 */
@RestController
@RequestMapping("/api")
public class MainController {

    @Reference(timeout = 2000)
    private EmailService emailService;
    @Reference(timeout = 4000, retries = 0)
    private CodeDubboService codeDubboService;
    @Reference(timeout = 2000)
    private UserDubboService userDubboService;
    @GetMapping("/test")
    public String test(){
        return "test";
    }

    @GetMapping("/email/{email}/{code}")
    public Boolean email(@PathVariable String email, @PathVariable String code){
        return emailService.email(email, code);
    }

    @GetMapping("/code/create/{email}")
    public Boolean create(@PathVariable String email){
        System.out.println("email:" + email);
        return codeDubboService.create(email);
    }

    @GetMapping("/code/validate/{email}/{code}")
    public Integer validate(@PathVariable String email, @PathVariable String code){
        System.out.println("email:" + email +  " code:" + code);
        return codeDubboService.validate(email, code);
    }

    @GetMapping("/user/login/{email}/{password}")
    public String login(@PathVariable String email, @PathVariable String password, HttpServletResponse response) {
        String token = userDubboService.login(email, password);
        if(token!=null && !token.equals("")) {
            System.out.println("token is null!!");
            Cookie cookie = new Cookie("token", token);
            cookie.setPath("/");
            response.addCookie(cookie);
            System.out.println(token);
            return email;
        }

        return "";
    }
    @GetMapping("/user/info/{token}")
    public String info(@PathVariable String token) {
        return userDubboService.info(token);
    }

    @GetMapping("/user/isRegistered/{email}")
    public Boolean isRegistered(@PathVariable String email) {
        return userDubboService.isRegistered(email);
    }

    @GetMapping("/user/register/{email}/{password}/{code}")
    public Boolean register(@PathVariable String email, @PathVariable String password, @PathVariable String code) {
        return userDubboService.register(email, password, code);
    }
}
